// 数据库初始化脚本
const mysql = require('mysql');
const fs = require('fs');
const path = require('path');

// 读取SQL文件
const sqlFilePath = path.join(__dirname, 'init_db.sql');
const sqlContent = fs.readFileSync(sqlFilePath, 'utf8');

// 连接数据库配置
const connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '123456'
});

// 连接数据库
connection.connect((err) => {
    if (err) {
        console.error('数据库连接失败:', err);
        process.exit(1);
    }
    console.log('数据库连接成功');
    
    // 执行SQL语句
    const sqlStatements = sqlContent.split(';').filter(Boolean);
    
    // 按顺序执行每个SQL语句
    let index = 0;
    const executeNext = () => {
        if (index >= sqlStatements.length) {
            console.log('数据库初始化完成');
            connection.end();
            return;
        }
        
        const sql = sqlStatements[index].trim();
        if (sql) {
            connection.query(sql, (err, result) => {
                if (err) {
                    console.error(`执行SQL语句失败 (${index + 1}):`, sql, err);
                    connection.end();
                    return;
                }
                console.log(`SQL语句执行成功 (${index + 1}):`, sql);
                index++;
                executeNext();
            });
        } else {
            index++;
            executeNext();
        }
    };
    
    executeNext();
});